<template>
    <div>
        <div class="section header">
            <h2 class="title has-text-entered dividing-header">UpVote! 💯</h2>
        </div>
        <div class="content">
            <post v-for="item in sortedItems" :item="item" :key="item.id"></post>
            <SubmitBox @submittedPost="createPost"></SubmitBox>
        </div>
        <div class="footer">
            <img src="https://bulma.io/images/made-with-bulma.png" alt="" width="128" height="24">
        </div>
    </div>
</template>

<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator'
import Post from '@/components/Post.vue'
import { Item } from '@/components/classes/Item'
import SubmitBox from '@/components/SubmitBox.vue'

@Component({
    name:"UpVote",
    components:{
        Post,
        SubmitBox
    }
})
export default class UpVote extends Vue {
    items:Array<Item> = [];
    public createPost(post:Item):void{
        post.votes = 0;
        post.id = this.numOfSubmissions + 1;
        this.items.push(post);
    }

    created():void{
        this.$http.get("/json/seed.json",{
            method:"get"
        }).then(({data}) =>{
            let posts = data.posts;
            posts.forEach((item:any) =>{
                this.items.push(item as Item);
            })
        })
        .catch((error:any) =>{
            console.log(error);
        });
    }

    get sortedItems():Item[]{
        return this.items.slice(0).sort((a,b) =>{
            return b.votes - a.votes
        });
    }

    get numOfSubmissions(){
        return this.items.length;
    }
}
</script>

<style scoped>
.header{
    padding: 3rem 1rem 1.5rem;
}
.footer{
    padding: 1rem;
}
</style>
